package pers.gxm.security.hello.listener;

import org.apache.catalina.security.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.web.context.support.SecurityWebApplicationContextUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import pers.gxm.security.hello.pojo.LoginUser;
import pers.gxm.security.hello.pojo.UserLoginLog;
import pers.gxm.security.hello.service.UserLoginLogService;
import pers.gxm.security.hello.utils.IpUtil;

import javax.servlet.http.HttpServletRequest;

@Component
public class AuthenticationSuccessListener implements ApplicationListener<AuthenticationSuccessEvent> {
    @Autowired
    private UserLoginLogService userLoginLogService;


    @Override
    public void onApplicationEvent(AuthenticationSuccessEvent event) {
//        Object principal1 = event.getAuthentication().getPrincipal();
        LoginUser principal = (LoginUser) event.getAuthentication().getPrincipal();
        UserLoginLog userLoginLog = new UserLoginLog();
        userLoginLog.setUserId(principal.getUser().getId());
        userLoginLog.setUsername(principal.getUser().getUserName());
//        RequestContextHolder.getRequestAttributes()
//        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = IpUtil.getRealIp();
        userLoginLog.setLoginIp(ip);
        userLoginLog.setLoginStatus(1);
        userLoginLog.setRemark(String.format("username:%s;message:登录成功",principal.getUser().getUserName()));
        userLoginLogService.save(userLoginLog);

    }
}
